﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using STX.Domain;
using STX.Service;
using STX.Lib.Security;
using STX.Lib.Caching;
using Autofac;

namespace STX.Web.Framework
{
    public class AdminContext
    {
        public ICacheProvider Cache { get; set; }
        public TabAdministratorService TabAdministratorService { get; set; }

        public TabAdministrator CurrentUser
        {
            get
            {
                var sessionId = System.Web.HttpContext.Current.Session.SessionID;
                var user = Cache.Get<TabAdministrator>(sessionId);
                if (user != null) return user;
                var uid = Lib.Web.Cookie.Instance.Get("STX_UId");
                var token = Lib.Web.Cookie.Instance.Get("STX_Token");
                if (uid.IsNullOrEmpty() || token.IsNullOrEmpty())
                {
                    return null;
                }
                var decryptUid = DESEncrypt.Decrypt(uid,"Msf89WK0","9iwsAF6r");
                var decryptToken = DESEncrypt.Decrypt(token, "6Fofv48x", "fS4Fisdf");

                TabAdministratorService.LoginByToken(decryptUid, decryptToken, (model) =>
                {
                    SetTicket(model);
                    user = model;
                });
                if (user == null)
                {
                    return null;
                }
                return user;
            }
        }

        public void SetTicket(TabAdministrator model)
        {
            if (model == null)
            {
                throw new Exception("找不到该用户");
            }
            STX.Lib.Web.Cookie.Instance.Set("STX_UId", DESEncrypt.Encrypt(model.UserName, "Msf89WK0", "9iwsAF6r"), true);
            STX.Lib.Web.Cookie.Instance.Set("STX_Pwd", DESEncrypt.Encrypt(HashEncrypt.MD5("OIFIOD%^%^^%&*)(*&"), "SFjh21f9", "dffs8SF0"), true);
            STX.Lib.Web.Cookie.Instance.Set("STX_Token", DESEncrypt.Encrypt(model.Token, "6Fofv48x", "fS4Fisdf"), true);
            var sessionId = System.Web.HttpContext.Current.Session.SessionID;
            Cache.Set(sessionId, model);
        }

        public void RemoveTicket()
        {
            var sessionId = System.Web.HttpContext.Current.Session.SessionID;
            Cache.Remove(sessionId);
            STX.Lib.Web.Cookie.Instance.Remove("STX_UId");
            STX.Lib.Web.Cookie.Instance.Remove("STX_Pwd");
            STX.Lib.Web.Cookie.Instance.Remove("STX_Token");
        }

        public bool AdminIsLogin
        {
            get
            {
                var sessionId = System.Web.HttpContext.Current.Session.SessionID;
                var user = Cache.Get<TabAdministrator>(sessionId);
                return null != user;
            }
        }

    }
}
